// BluetoothDemo.java
package v2;

import org.freedesktop.dbus.exceptions.DBusException;
import org.freedesktop.dbus.types.Variant;

import java.util.Map;

/**
 * 完整的蓝牙数据收发演示 (dbus-java 3.3.2)
 */
public class BluetoothDemo {

    public static void main(String[] args) {
        try {
            System.out.println("🎯 启动蓝牙数据收发演示...\n");
            // 创建数据接收器
            BluetoothDataReceiver receiver = new BluetoothDataReceiver();
            // 添加数据监听器
            receiver.addListener(new DemoBluetoothListener());

            // 创建数据发送器
            BluetoothDataSender sender = new BluetoothDataSender();

            // 在后台启动接收器
            Thread receiverThread = new Thread(() -> {
                try {
                    receiver.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            receiverThread.setDaemon(true);
            receiverThread.start();

            // 等待接收器启动
            Thread.sleep(2000);

            // 演示发送数据
            demonstrateSending(sender);

            // 保持程序运行一段时间
            System.out.println("\n⏳ 运行中，等待接收蓝牙数据...");

            while (true) {
                Thread.sleep(2000);
            }



        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("\n🎉 演示完成");
        }
    }

    private static void demonstrateSending(BluetoothDataSender sender) {
        try {
            // 演示发送数据
            System.out.println("\n=== 🚀 演示发送数据 ===");

            String testDeviceMac = "40_DC_A5_26_54_8A".replace("_", ":");

            // 尝试连接设备
            sender.connectDevice(testDeviceMac);
            Thread.sleep(1000);

            // 发送 WiFi 配置
            sender.sendWifiConfig(testDeviceMac, "HUAWEI_H122_D3E9", "Cytech@324");
            Thread.sleep(1000);

//            // 发送控制命令
//            sender.sendControlCommand(testDeviceMac, "RESTART");
//            Thread.sleep(1000);
//
//            sender.sendControlCommand(testDeviceMac, "SET_MODE", "HIGH", "FAST");
//            Thread.sleep(1000);

            // 发送自定义数据
            sender.sendDataToDevice(testDeviceMac, "Hello from dbus-java 3.3.2!");
            Thread.sleep(1000);

            // 断开连接
            sender.disconnectDevice(testDeviceMac);

        } catch (Exception e) {
            System.err.println("演示发送数据失败: " + e.getMessage());
        }
    }

    /**
     * 演示用的蓝牙数据监听器
     */
    static class DemoBluetoothListener implements BluetoothDataListener {
        @Override
        public void onBluetoothDataReceived(String deviceMac, Map<String, Variant<?>> data) {
            System.out.println("\n🎯 监听器收到数据:");
            System.out.println("来自设备: " + deviceMac);
            System.out.println("数据内容: " + data);

            // 处理具体的数据
            data.forEach((key, value) -> {
                if (key.equals("ServiceData") || key.equals("ManufacturerData")) {
                    System.out.println(">>> 处理业务数据: " + value.getValue());
                }

                // 检查是否包含 WiFi 配置
                if (value.getValue() instanceof String) {
                    String strValue = (String) value.getValue();
                    if (strValue.contains("WIFI")) {
                        System.out.println(">>> 发现 WiFi 配置: " + strValue);
                        processWifiConfig(strValue);
                    }
                }
            });
        }

        private void processWifiConfig(String config) {
            try {
                String[] parts = config.split(":");
                if (parts.length >= 3) {
                    String ssid = parts[1];
                    String password = parts[2];
                    System.out.println("📶 解析出 WiFi - SSID: " + ssid + ", Password: " + password);
                }
            } catch (Exception e) {
                System.err.println("解析 WiFi 配置失败: " + e.getMessage());
            }
        }

        @Override
        public void onDeviceConnectionChanged(String deviceMac, boolean connected) {
            System.out.println("\n🔗 设备连接状态变化:");
            System.out.println("设备: " + deviceMac);
            System.out.println("状态: " + (connected ? "✅ 已连接" : "❌ 已断开"));
        }

        @Override
        public void onNewDeviceDiscovered(String deviceMac) {
            System.out.println("\n🔍 发现新设备: " + deviceMac);
        }
    }
}